const fs = require("fs");
const path = require("path");
const { fileStorageDir } = require("@/config/index");
const excuteSql = require("../../utils/connection");

// 读取 SQL 文件
async function readSqlFile(filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, "utf8", (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
}

// 初始化数据库
async function initializeDatabase() {
  try {
    const sql = await readSqlFile(path.join(__dirname, "fileserve.sql"));
    const result = await excuteSql(sql + "select * from fileservespacetable;");
    if (result.length > 0) {
      result[result.length - 1].forEach((space) => {
        if (!fs.existsSync(fileStorageDir + "/" + space.space_id)) {
          fs.mkdirSync(fileStorageDir + "/" + space.space_id, {
            recursive: true,
          });
        }
      });
    }
  } catch (error) {
    console.log("数据库初始化失败或文件空间创建失败:", error);
  }
}

module.exports = initializeDatabase;
